package com.novax.ex.activity.provider.service;

import com.alibaba.fastjson.JSON;
import com.novax.ex.activity.infrastructure.entity.BeebUser;
import com.novax.ex.activity.infrastructure.entity.DreamBfUser;
import com.novax.ex.activity.infrastructure.mapper.BeebUserMapper;
import com.novax.ex.activity.infrastructure.mapper.DreamBfUserMapper;
import com.novax.ex.activity.open.model.query.BeebUserQuery;
import com.novax.ex.activity.provider.api.UserApi;
import com.novax.ex.activity.provider.api.UserAssetApi;
import com.novax.ex.activity.provider.api.model.AssetChangeRequest;
import com.novax.ex.activity.provider.api.model.BeebMaxMinIdsResponse;
import com.novax.ex.activity.provider.api.model.BeebUserResponse;
import com.novax.ex.activity.provider.handler.provider.BeebUserProvider;
import com.novax.ex.common.base.BaseMapper;
import com.novax.ex.common.base.BaseService;
import com.novax.ex.common.results.ReturnResult;
import com.novax.ex.common.util.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import jakarta.annotation.Resource;
import java.math.BigDecimal;
import java.time.Duration;
import java.time.Instant;
import java.util.*;
import java.util.concurrent.atomic.LongAdder;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @Description beeb空投项目 用户
 * @Author zhaolei
 * @Date 10/24/24 3:26 PM
 * @Version 1.0
 */
@Service
@Slf4j
public class BeebUserService extends BaseService {
    @Resource
    private UserApi userApi;
    @Resource
    private BeebUserProvider beebUserProvider;
    @Resource
    private DreamBfUserMapper dreamBfUserMapper;
    @Resource
    private UserAssetApi userAssetApi;
    @Resource
    private BeebUserMapper beebUserMapper;

    public static LongAdder sendCount = new LongAdder();//发送计数器
    public static LongAdder receiveCount = new LongAdder();//接收计数器

    @Override
    protected BaseMapper getBaseMapper() {
        return null;
    }

    //curl -X GET -H  "Accept:*/*" -H  "Content-Type:application/x-www-form-urlencoded" "http://localhost:51041/v3/private/beeb/user/init?startTime=2024-10-20%2000:00:00&pageSize=1000"
    public void init(BeebUserQuery query) {
        //获取批次开始时间
        String startTime = query.getStartTime();
        if (Objects.isNull(startTime)) {
            startTime = "2024-10-20 00:00:00";
        }
        //拉取数据
        initData(startTime, query.getPageSize());
    }

    public void initData(String time, Long pageSize) {
        if (StringUtils.isBlank(time)) {
            time = DateUtil.getDateStringSeq(new Date(), DateUtil.DEFAULT_DATE);
        }
        Long idStart = 0l;
        Long idEnd = 0l;
        int size = 0;
        ReturnResult<BeebMaxMinIdsResponse> beebMinMaxIds = userApi.getBeebMinMaxIds(time);
        if (beebMinMaxIds.isSuccess()) {
            idStart = beebMinMaxIds.getData().getMin() - 1;
            idEnd = beebMinMaxIds.getData().getMax();
            log.info("本批次数据起止:--idStart:" + idStart + "--idEnd:" + idEnd);
        }
        Instant start = Instant.now();
        while (idStart < idEnd) {
            ReturnResult<List<BeebUserResponse>> beebData = userApi.getBeebData(idStart, pageSize);
            if (beebData.isSuccess()) {
                List<BeebUserResponse> list = beebData.getData();
                if (Objects.isNull(list) || list.size() == 0) {
                    idStart = idEnd;
                } else {
                    idStart = list.get(list.size() - 1).getId();
                    initOld(list);
                }
                size = size + list.size();
            }
            log.info("当前截止Id:" + idStart);
            try {
                Thread.sleep(1000);
            } catch (Exception ex) {

            }
        }
        log.info("初始化拉取处理完毕:" + DateUtil.getDateStringSeq(new Date(), DateUtil.DEFAULT_TIME) +
                "--发送总数:" + size +
                "--耗时:" + Duration.between(start, Instant.now()).toMillis() + " milliseconds"
        );
    }

    private void initOld(List<BeebUserResponse> dataList) {
        for (BeebUserResponse userResponse : dataList) {
            sendCount.increment();
            beebUserProvider.sendMsg(userResponse.getId().toString(), JSON.toJSONString(userResponse));
        }
    }

    /**
     * @description: 执行初始化
     * @author: Wade
     * @date: 10/24/24 5:10 PM
     * @param: [msg]
     * @return: void
     **/
    @Transactional(rollbackFor = RuntimeException.class)
    public void exec(String msg) {
        receiveCount.increment();
        BeebUserResponse entity = JSON.parseObject(msg, BeebUserResponse.class);
        List<DreamBfUser> dreamBfUsers = null;
        if (StringUtils.isNotBlank(entity.getAreaCode()) && StringUtils.isNotBlank(entity.getPhone())) {
            //说明手机号不为空,并且是巴西用户
            /**
             关于数据库中手机位数的处理

             处理方法：从10位变11位

             针对于 1234567890 这样的 10 位电话号码，我们需要用原来的10位号码再加上 2 种衍生号再额外去匹配；其中匹配的优先级按照顺序如下：

             1234567890 > 12934567890（第二位后面加9）> 01234567890（首字母加0）

             处理方法：从11位变10位

             针对于 12345678901 这样的 11位电话号码，我们需要用原来的11位号码再加上 2 种衍生号再额外去匹配；其中匹配的优先级按照顺序如下：

             12345678901 > 1245678901（去掉第3位的数字9；但如果这个号码的第3位不是9，我们就不做处理） > 2345678901（去掉第1位的数字）

             注意：以上两种处理方法是有优先级顺序的。平台先用第一位置的号码去匹配，如果能匹配上就不用管后面的位置了。如果没有，就再用第二位置的号码去匹配，以此类推。
             **/
            if (entity.getAreaCode().equals("55")) {
                if (entity.getPhone().length() == 10) {
                    // 原始：1234567890，变形后 12934567890，01234567890
                    /*List<String> list = Arrays.asList(
                            entity.getPhone(),
                            "0" + entity.getPhone(),
                            entity.getPhone().substring(0,2)+"9"+entity.getPhone().substring(2));*/
                    //dreamBfUsers = dreamBfUserMapper.selectByPhoneIn(list);
                    //以优先级进行处理
                    dreamBfUsers = dreamBfUserMapper.selectByPhone(entity.getPhone());
                    if(CollectionUtils.isEmpty(dreamBfUsers)){
                        //说明优先级1的没查到
                        dreamBfUsers = dreamBfUserMapper.selectByPhone(entity.getPhone().substring(0,2)+"9"+entity.getPhone().substring(2));
                        if(CollectionUtils.isEmpty(dreamBfUsers)){
                            //说明优先级2的没查到
                            dreamBfUsers = dreamBfUserMapper.selectByPhone("0" + entity.getPhone());
                        }
                    }
                } else {
                    //原始： 12345678901，变形后：2345678901
                    //原始： 12945678901，变形后：1245678901 2945678901
                    dreamBfUsers = dreamBfUserMapper.selectByPhone(entity.getPhone());
                    if(CollectionUtils.isEmpty(dreamBfUsers)){
                        //说明优先级1的没查到
                        //判断第三位是否为9
                        String isNine = entity.getPhone().substring(2, 3);
                        if(isNine.equals("9")){
                            dreamBfUsers = dreamBfUserMapper.selectByPhone(entity.getPhone().substring(0,2)+entity.getPhone().substring(3));
                        }
                        if(CollectionUtils.isEmpty(dreamBfUsers)){
                            //说明优先级2的没查到
                            dreamBfUsers = dreamBfUserMapper.selectByPhone(entity.getPhone().substring(1));
                        }
                    }
                }
            }
            if (StringUtils.isNotBlank(entity.getEmail())) {
                if (Objects.isNull(dreamBfUsers)) {
                    dreamBfUsers = new ArrayList<>();
                }
                List<DreamBfUser> emList = dreamBfUserMapper.selectByEmail(entity.getEmail());
                if (Objects.nonNull(emList) && emList.size() > 0) {
                    dreamBfUsers.addAll(emList);
                    //过滤可能存在重复的id
                    dreamBfUsers = dreamBfUsers.stream()
                            .collect(Collectors.toMap(DreamBfUser::getId, Function.identity(), (existing, replacement) -> existing))
                            .values()
                            .stream()
                            .collect(Collectors.toList());

                }
            }

        } else {
            if (StringUtils.isNotBlank(entity.getEmail())) {
                dreamBfUsers = dreamBfUserMapper.selectByEmail(entity.getEmail());
            }
        }
        if (Objects.nonNull(dreamBfUsers) && dreamBfUsers.size() > 0) {
            //计算总共要发放的总额
            BigDecimal total = BigDecimal.ZERO;
            Long orderId = 0l;
            boolean check = true;
            for (DreamBfUser dreamBfUser : dreamBfUsers) {
                //如果本系统ID没有说明是需要进行初始化的
                //只检查此项，只要有SuperexUserId存在就代表已经空投过了，不管后面成功没成功，没成功的到时候想办法手动处理
                //并且下面的转账也是当返回操作资产成功了，才会进行保存，否则不会进行任何操作此对象
                if (Objects.nonNull(dreamBfUser.getSuperexUserId())) {
                    log.error("此账户的beeb被处理过:" + JSON.toJSONString(dreamBfUser));
                    check = false;
                    break;//直接结束，因为查到了，本批次有数据被处理过
                }
                total = total
                        .add(dreamBfUser.getUsableMoney())
                        .add(dreamBfUser.getBuyMoney())
                        .add(dreamBfUser.getPositionRevenue())
                        .add(dreamBfUser.getCurrentCom());
                dreamBfUser.setSuperexUserId(entity.getId());
                orderId = dreamBfUser.getId().longValue();
            }
            //数量太少了，直接过滤掉
            total = total.multiply(BigDecimal.TEN);
            if (total.compareTo(new BigDecimal("0.0001")) < 0) {
                check = false;
            }
            if (check) {
                //插入
                for (DreamBfUser dreamBfUser : dreamBfUsers) {
                    dreamBfUserMapper.updateByPrimaryKeySelective(dreamBfUser);
                }
                //插入beeb_user
                BeebUser user = new BeebUser();
                /**
                 * 用户id
                 */
                user.setUserId(entity.getId());

                /**
                 * 区号
                 */
                user.setAreaCode(entity.getAreaCode());

                /**
                 * 手机号
                 */
                if(StringUtils.isNotBlank(entity.getPhone())) {
                    user.setPhone(entity.getPhone());
                }

                /**
                 * 邮箱
                 */
                if(StringUtils.isNotBlank(entity.getEmail())) {
                    user.setEmail(entity.getEmail());
                }

                /**
                 * 空投总量
                 */
                user.setTotal(total);

                /**
                 * 已空投总量
                 */
                user.setSendTotal(total);

                /**
                 * 是否已空投 0:未空投 1:已空投
                 */
                user.setSendStatus(1);
                beebUserMapper.insertSelective(user);
                //加资产放最后，防止出错后，调用了加资产导致给用户重复加
                ReturnResult result = addAsset(entity.getId(), orderId, "beeb", total);
                if (!result.isSuccess()) {
                    log.error("增加此账户的beeb冻结资产失败:" + msg);
                }
            }
        }
    }

    /**
     * beeb 发放到冻结
     */
    Integer BEENB_FROZEN = 102;
    /**
     * beeb 发放到解冻
     */
    Integer BEENB_UNFREEZE = 103;

    public ReturnResult addAsset(Long userId, Long orderId, String currency, BigDecimal amount) {
        AssetChangeRequest request = new AssetChangeRequest();
        // 用户id
        request.setUserId(userId);
        // 订单id
        request.setOrderId(orderId);
        // 支付币种
        request.setCurrency(currency);
        // 标记
        request.setSymbol(currency);
        // 总支付金额
        request.setAmount(amount);
        // 类型
        request.setOperation(BEENB_FROZEN);
        return userAssetApi.assetChange(request);
    }

    /**
     * 解锁
     */
    public ReturnResult unfrozen(AssetChangeRequest request) {
        request.setOperation(BEENB_UNFREEZE);
        return userAssetApi.assetChange(request);
    }

    /*public static void main(String[] args) {
        String phone = "1234567890";
        List<String> list = Arrays.asList(
                phone,
                "0" + phone,
                phone.substring(0,2)+"9"+phone.substring(2));
        System.out.println(list.toString());
        System.out.println(phone.substring(2,3));
        if(phone.substring(2,3).equals("9")){
            System.out.println(phone.substring(0,2)+phone.substring(3));
        }else{
            System.out.println(phone.substring(1));
        }
    }*/
}
